/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmail.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author iflamed
 */
public class XmlData {

    private Document doc;
    private File xmlfile;

    /**
     *
     * @param file String the file path contain the file name
     * @throws JDOMException
     * @throws IOException
     */
    public XmlData(String file) throws JDOMException, IOException {
        xmlfile = new File(file);
        SAXBuilder builder = new SAXBuilder();
        doc = builder.build(xmlfile);
    }

    /**
     *
     * @param file
     * <code>File<code> file
     * @throws JDOMException
     * @throws IOException
     */
    public XmlData(File file) throws JDOMException, IOException {
        xmlfile = file;
        SAXBuilder builder = new SAXBuilder();
        doc = builder.build(xmlfile);
    }

    private void createXml() throws IOException {
        Element root, stuNumber, stuName, assignments, assignment,
                score, attachs, attach, fileName, filePath;
        root = new Element("student-info");
        stuNumber = new Element("student-number");
        stuName = new Element("student-name");
        assignments = new Element("assignments");
        assignment = new Element("assignment");
        score = new Element("score");
        attachs = new Element("attachs");
        attach = new Element("attach");
        fileName = new Element("filename");
        filePath = new Element("filepath");
        score.setText("0");
        doc.setRootElement(root);
        root.addContent(stuNumber);
        root.addContent(stuName);
        root.addContent(score);
        root.addContent(assignments);
        Format format = Format.getCompactFormat();
        format.setEncoding("GB2312"); //设置xml文件的字符为gb2312
        format.setIndent("    "); //设置xml文件的缩进为4个空格
        XMLOutputter XMLOut = new XMLOutputter(format);//元素后换行一层元素缩四格
        XMLOut.output(doc, new FileOutputStream(xmlfile));
    }

    /**
     *
     * @param assignname assignment name like 作业几
     * @param intScore the score of this assignment
     * @param attachMap the
     * <code>TreeMap<code> contains the attachment name and file path
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void insertXml(String assignname, int intScore, TreeMap<String, String> attachMap) throws FileNotFoundException, IOException {
        Element root, assignments, assignment, totalScore, assign,
                score, attachs, attach, fileName, filePath, ittemp, number;
        int totalscore;
        int scoretemp = 0;
        root = doc.getRootElement();
        number = root.getChild("student-number");
        assignments = root.getChild("assignments");
        Students allstu = new Students();
        int count = allstu.getAssginCount(number.getText()) + 1;
        //检查是否已经存在这个作业
        List<Element> assigns = assignments.getChildren();
        Iterator ithas = assigns.iterator();
        int i;
        boolean remove = false;
        for (i = 0; ithas.hasNext(); i++) {
            ittemp = (Element) ithas.next();
            if (ittemp.getChildText("assign").equals(assignname)) {
                remove = true;
                scoretemp = Integer.parseInt(ittemp.getChildText("score"));
                break;
            }
        }
        if (remove) {
            assigns.remove(i);
        }
        //检查已经存在这个作业完成
        totalScore = root.getChild("totalscore");
        totalscore = Integer.parseInt(totalScore.getText());
        totalscore = totalscore + intScore - scoretemp;
        totalScore.setText(Integer.toString(totalscore));
        assignment = new Element("assignment");
        assign = new Element("assign");
        assign.setText(assignname);
        score = new Element("score");
        score.setText(Integer.toString(intScore));
        attachs = new Element("attachs");
        Iterator it = attachMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            attach = new Element("attach");
            fileName = new Element("filename");
            filePath = new Element("filepath");
            fileName.setText(pairs.getKey().toString());
            filePath.setText(pairs.getValue().toString());
            attach.addContent(fileName);
            attach.addContent(filePath);
            attachs.addContent(attach);
        }
        assignment.addContent(assign);
        assignment.addContent(score);
        assignment.addContent(attachs);
        assignments.addContent(assignment);
        Format format = Format.getCompactFormat();
        format.setEncoding("GB2312"); //设置xml文件的字符为gb2312
        format.setIndent("    "); //设置xml文件的缩进为4个空格
        XMLOutputter outputter = new XMLOutputter(format);
        outputter.output(doc, new FileOutputStream(xmlfile));
        allstu.updateStudent(number.getText(), "totalscore", Integer.toString(totalscore));
        if (!remove) {
            allstu.updateStudent(number.getText(), "assigncount", Integer.toString(count));
        }
    }

    /**
     *
     * @param assignname <String> the assignment name
     * @param value <String> the new value of the attribute
     * @return
     */
    public boolean updateScore(String assignname, String value) throws IOException {
        try {
            Element root, assignments, assignment, totalScore;
            List<Element> assigns;
            root = doc.getRootElement();
            assignments = root.getChild("assignments");
            totalScore = root.getChild("totalscore");
            String number = root.getChildText("student-number");
            int totalscore, score;
            totalscore = Integer.parseInt(totalScore.getText());
            assigns = assignments.getChildren();
            Iterator it = assigns.iterator();
            boolean isupdate = false;
            while (it.hasNext()) {
                assignment = (Element) it.next();
                if (assignment.getChild("assign").getText().equals(assignname)) {
                    score = Integer.parseInt(assignment.getChild("score").getText());
                    totalscore = totalscore - score + Integer.parseInt(value);
                    totalScore.setText(Integer.toString(totalscore));
                    assignment.getChild("score").setText(value);
                    isupdate = true;
                    break;
                }
            }
            Format format = Format.getCompactFormat();
            format.setEncoding("GB2312"); //设置xml文件的字符为gb2312
            format.setIndent("    "); //设置xml文件的缩进为4个空格
            XMLOutputter outputter = new XMLOutputter(format);
            outputter.output(doc, new FileOutputStream(xmlfile));
            Students allstu = new Students();
            allstu.updateStudent(number, "totalscore", Integer.toString(totalscore));
            return isupdate;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XmlData.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    public List getDetail() {
        Element root;
        List<Element> assigns;
        root = doc.getRootElement();
        assigns = root.getChildren();
        System.out.println(assigns.get(1).getText());
        return assigns;
    }
}
